<template>
	<view class="mains">
		<view class="card_box" v-show="showPages == 1">
			<view class="top_card">
				<view class="card_title">
					随访计划名称
				</view>
				<view class="inputStyle">
					<u-input v-model="form.name" maxlength="30" :border="false"
						placeholder-style="color: #C1C1C1;font-size:32rpx" placeholder="请输入随访计划名称"></u-input>
				</view>
			</view>
			<view class="top_card" v-if="teamId">
				<view class="card_title">
					执行成员
				</view>
				<view class="inputStyle">
					<view style="width: 85%;" v-if="userListSelected.length>0">
						<scroll-view scroll-x="true">
							<view class="tags_box">
								<view class="tags" v-for="v,k in userListSelected" :key="v.userName"
									@click="delUser(v,k)">
									<view class="tags_title">
										{{v.userName}}
									</view>
									<view class="x_img">
										<u-image :src="x" width="36rpx" height="36rpx"></u-image>
									</view>
								</view>
							</view>
						</scroll-view>
					</view>
					<view class="line_title" style="color:#C1C1C1 ;" v-if="userListSelected.length==0">
						请选择执行成员
					</view>
					<view class="arrow_width" @click="upUserFilter">
						<u-icon :name="userArrow" size="40rpx" color="#CCCCCC"></u-icon>
					</view>
				</view>
			</view>

			<view class="top_card">
				<view class="card_title">
					目标患者
				</view>
				<view class="inputStyle">
					<view style="width: 85%;" v-if="huanzheListSelected.length>0">
						已选择{{huanzheListSelected.length}}人
					</view>
					<view style="width: 85%;" v-if="markSelected.length>0">
						已选择{{markSelected.length}}标签
					</view>
					<view class="line_title" style="color:#C1C1C1 ;"
						v-if="huanzheListSelected.length==0 && markSelected.length == 0">
						请选择目标患者或标签
					</view>

					<view class="arrow_width" @click="showPages = 2">
						<u-icon :name="userArrow" size="40rpx" color="#CCCCCC"></u-icon>
					</view>
				</view>
			</view>

			<view class="top_card">
				<view class="card_title">
					计划周期
				</view>
				<view class="inputStyle" @click="upTimerPicker">
					<view style="width: 85%;" v-if="projectTime.startDate.length>0">
						{{projectTime.startDate}} <span class="p-l-6 p-r-6">至</span> {{projectTime.endDate}}
					</view>
					<view class="line_title" style="color:#C1C1C1 ;" v-if="projectTime.startDate.length==0">
						请选择计划开始时间和结束时间
					</view>
					<view class="">
						<u-image :src="dateIcon" width="40rpx" height="40rpx"></u-image>
					</view>
				</view>
				<view class="tips">
					提示：计划周期以<span class="primary">天</span>为维度，<span class="primary">00:00:00</span> 开始，<span
						class="primary">23:59:59</span>结束
				</view>
			</view>

			<view class="job_rule">
				<view class="">
					任务规则
				</view>
				<view class="job_add" @click="toJobRule" v-if="!isShow">
					＋添加任务规则
				</view>
			</view>

			<view class="rule_box">
				<view class="rule_card" v-for="n in jobList" :key="n.jobName">
					<view class="rule_step">
						<view class="dot">
							<u-image :src="setpTime" width="24rpx" height="24rpx"></u-image>
							<view class="time_title">
								{{n.jobStartTime}}
							</view>
						</view>

						<view class="dash">

						</view>
					</view>
					<view class="rule_content">
						<view class="">
							<view class="rule_content_title">
								<view class="base_icon zhouqi"
									:class="{'zhouqi':n.jobType == 2,'dingshi':n.jobType == 1}">
									{{n.jobType == 1 ? '定时' : '周期'}}
								</view>
								<view class="m-l-10">
									{{cultString(n.jobName,14)}}
								</view>
							</view>
							<view class="rule_content_details">
								{{cultString(n.jobContent,35)}}
							</view>
							<view class="rule_content_action">
								<view class="edit" @click="goEdit(n)" v-if="!isShow">
									编辑
								</view>
								<view class="del" @click="goDel(n)" v-if="!isShow">
									删除
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

		</view>
		<!-- 目标患者页面 -->
		<mubiao-huanzhe @conditions="conditions" v-show="showPages == 2"></mubiao-huanzhe>

		<u-popup v-model="showMark" border-radius="40" mode="top" :safe-area-inset-bottom="true"
			:mask-close-able="false">
			<markComponents @closeMark="closeMark" ref="markChild" @Markconfirm="Markconfirm"></markComponents>
		</u-popup>

		<go-nav v-show="showPages == 1"></go-nav>

		<my-time-picker :isTimePickerShow="isTimePickerShow" title="选择计划周期" @confirm="timeConfirm" @close="timeClose"
			:Timehuixian="Timehuixian"></my-time-picker>

		<u-popup v-model="showUser" mode="top" border-radius="40" :safe-area-inset-bottom="true"
			:mask-close-able="false">
			<huanzhe-team-list title="选择执行成员" @close="Userconfirm " @confirm="Userconfirm" mytype="2"
				ref="teamChild"></huanzhe-team-list>
		</u-popup>

		<u-popup v-model="showPatient" mode="top" border-radius="40" :safe-area-inset-bottom="true"
			:mask-close-able="false">
			<team-list-vuex title="患者列表" @close="PatientConfirm" @confirm="PatientConfirm" mytype="2"
				ref="Patient"></team-list-vuex>
		</u-popup>
		<bottom-button @confirm="btConfirm" :inactive="inactive" v-if="showPages == 1 && !isShow"></bottom-button>
		<bottom-button @confirm="btFilterConfirm" :inactive="false" v-if="showPages == 2"></bottom-button>
	</view>
</template>

<script>
	import markComponents from './component/mark-list/mark-list.vue'
	import teamListVuex from './component/team-list-vuex/team-list-vuex.vue'
	import register from '../../utils/register'
	import {
		addPlan,
		getFollowupPlanJobByPlanId,
		getFollowupPlanDetails,
		getTeamUserListByTeamId,
		getCustomerListByTeamOrUserId,
		tagedList,
		putPlan
	} from '@/api/index.js'
	export default {
		components: {
			'markComponents': markComponents,
			'team-list-vuex': teamListVuex
		},
		data() {
			return {
				isTimePickerShow: false,
				dateIcon: require('@/static/icon/date@2x.png'),
				setpTime: require('@/static/icon/Time node@2x.png'),
				showUser: false,
				showPatient: false,
				ActionUser: false,
				userArrow: 'arrow-down',
				x: require('@/static/icon/x.png'),
				MarkSelectLength: 0,
				projectTime: {
					startDate: '',
					endDate: ''
				},
				form: {
					name: ''
				},
				userList: [],
				huanzheList: [],
				inactive: false,
				showPages: 1, //1表单页，2筛选页
				currentCondition: '', //huanzhe,biaoqian  选择患者弹窗或者标签弹窗
				showMark: false,
				MarkList: [],
				editTagIdList: [],
				edit: '', //接参？
				isShow: false, //查看
				planId: '',
				Timehuixian: '',
				teamId: '',
				externalUserId:''
			}
		},
		computed: {
			userListSelected: {
				get() {
					let arr = this.userList.filter(v => v.check == true)
					return arr
				}
			},
			markSelected() {
				return this.$store.state.doc.suifangUserListSelected
			},
			huanzheListSelected() {
				let arr = this.huanzheList.filter(v => v.check == true)
				this.$store.commit('SUIFANGhuanzheSelected', arr)
				return arr
			},
			cultString(val, num) {
				return (val, num) => {
					let myString = val.toString()
					if (val.length > num) {
						return val.slice(0, num) + '...'
					} else {
						return val
					}
				}
			},
			jobList: {
				get() {
					return this.$store.state.doc.JobList
				},
				set(val) {

				}
			}
		},
		onLoad(obj) {
			if (obj.planId) {
				this.planId = obj.planId
				this.getContent()
			}
			if (obj.isShow) this.isShow = JSON.parse(obj.isShow)
			if(obj.externalUserId){
				this.externalUserId = obj.externalUserId
				this.huixianPatient()
			} 
		},
		onShow() {
			if (uni.getStorageSync('myTeam')) { //有Team时，用teamId
				this.teamId = uni.getStorageSync('myTeam').data.id
			}
		},
		onReady() {
			if (this.planId) {
				uni.setNavigationBarTitle({
					title: '查看随访计划'
				});
			}
		},
		methods: {
			async getContent() {
				let res = await getFollowupPlanDetails(this.planId)
				this.form.name = res.data.planName //计划名称
				this.projectTime.startDate = res.data.planStartTime.split(' ')[0]
				this.projectTime.endDate = res.data.planEndTime.split(' ')[0]
				this.Timehuixian = {
					startDate: this.projectTime.startDate,
					endDate: this.projectTime.endDate
				}
				this.getAllzhixing(res.data.planUserName) //把执行成员传过去
				this.gethuanzhe(res.data.targetCustomerType) //目标患者回显
				this.ShowjobList()
				// planStartTime:this.projectTime.startDate,  //计划周期开始
				// planEndTime:this.projectTime.endDate, 
				//this.jobList = res.data
				//console.log(res);
			},
			async gethuanzhe(type) { //目标患者回显 2、患者标签 3、添加患者  targetCustomerType
				if (type == 2) { //患者标签
					const params = {
						planId: this.planId
					}
					let res = await tagedList(params)
					let arr = res.data.reduce((pre, value, index) => {
						const checkList = value.tagList.filter((v, k) => {
							return v.isCheck == "true"
						})
						checkList.forEach(v => {
							if (v.isCheck == "true") {
								v.check = true
							} else {
								v.check = false
							}
						})
						pre.push(...checkList)
						return pre
					}, [])
					if (arr.length > 0) {
						let tagList = arr.map(v => {
							return v.tagId
						})
						this.$store.commit('SUIFANGuserSelected', tagList) //回显标签列表
					}
				}
				if (type == 3) { //添加患者
					const params = {
						teamOrUserId: '',
						planId: this.planId,
						pageNum: 1,
						pageSize: 10000
					}
					if (uni.getStorageSync('myTeam')) { //有Team时，用teamId
						const teamId = uni.getStorageSync('myTeam').data.id
						this.teamId = teamId
						params['teamOrUserId'] = teamId
					} else { //没团队用userid
						let userId = uni.getStorageSync('userinfo').user.userId
						params['teamOrUserId'] = 0
					}
					let res = await getCustomerListByTeamOrUserId(params)
					if (res.rows.length > 0) {
						this.huanzheList = res.rows.map(v => { //目标患者输入框回显
							if (v.isCheck == true) {
								v.check = true
							}
							return v
						})
					}
					this.$store.commit('FilterTeamChoose', res.rows) //所选患者列表回显
				}
			},
			async huixianPatient(){
				const params = {
					teamOrUserId: '',
					planId: this.planId,
					pageNum: 1,
					pageSize: 10000
				}
				if (uni.getStorageSync('myTeam')) { //有Team时，用teamId
					const teamId = uni.getStorageSync('myTeam').data.id
					this.teamId = teamId
					params['teamOrUserId'] = teamId
				} else { //没团队用userid
					let userId = uni.getStorageSync('userinfo').user.userId
					params['teamOrUserId'] = 0
				}
				let res = await getCustomerListByTeamOrUserId(params)
				if (res.rows.length > 0) {
					this.huanzheList = res.rows.map(v => { //目标患者输入框回显
						if (v.externalUserId == this.externalUserId) {
							v.check = true
						}
						return v
					})
				}
				this.$store.commit('FilterTeamChoose', res.rows) //所选患者列表回显
			},
			async getAllzhixing(zhixingUser) { //执行成员回显
				const obj = {
					teamId: '',
					pageNum: 1,
					pageSize: 10000,
					planId: this.planId
				}
				if (uni.getStorageSync('myTeam')) {
					obj.teamId = uni.getStorageSync('myTeam').data.id
					let res = await getTeamUserListByTeamId(obj)
					this.userList = res.rows.map(v => {
						if (v.isSelect == true) {
							v.check = true
						} else {
							v.check = false
						}
						return v
					})
				}
				//console.log(res);
			},
			async ShowjobList() { //任务列表规则回显
				let res = await getFollowupPlanJobByPlanId(this.planId)
				if (res.code == 200) {
					this.$store.commit('SHOWJOBLISTALL', res.data)
				}
				//console.log(res,'任务规则回显');
			},
			async goEdit(obj) {
				if (this.planId) { //有值就是修改
					if (obj.jobType == 1) this.$store.commit('JOBTYPEShow', '定时任务')
					if (obj.jobType == 2) this.$store.commit('JOBTYPEShow', '周期任务')
				}
				let res = await this.$store.dispatch('editJobList', obj.jobName)
				if (res.find) {
					uni.navigateTo({
						url: `/pages/follow/rulejob?edit=1&jobName=${obj.jobName}`
					})
				}
				//console.log(res);
			},
			goDel(obj) {
				if (this.planId) { //编辑时需要填写删除的理由
					uni.navigateTo({
						url: `/pages/follow/deljob?id=${obj.id}&planId=${this.planId}`
					})
				} else {
					this.$store.commit('DELJOB', obj)
				}

			},
			legalTime(val) {
				const now = new Date();
				// 获取年份  
				const year = now.getFullYear();
				// 获取月份，注意月份是从0开始的，所以需要+1  
				const month = String(now.getMonth() + 1).padStart(2, '0');
				// 获取日期  
				const day = String(now.getDate()).padStart(2, '0');
				// 获取小时  
				const hour = String(now.getHours()).padStart(2, '0');
				// 获取分钟  
				const minute = String(now.getMinutes()).padStart(2, '0');
				//开始时间
				const pickStart = new Date(val.startDate)
				const startYear = pickStart.getFullYear();
				const startMonth = String(pickStart.getMonth() + 1).padStart(2, '0');
				const startDay = String(pickStart.getDate()).padStart(2, '0');
				//结束时间
				const pickEnd = new Date(val.endDate)
				const endYear = pickEnd.getFullYear();
				const endMonth = String(pickEnd.getMonth() + 1).padStart(2, '0');
				const endDay = String(pickEnd.getDate()).padStart(2, '0');
				//开始校验
				//console.log(day != startDay,pickStart.getTime())
				if (now.getTime() > pickStart.getTime() && day != startDay) {
					return false
				}
				//结束校验
				if (now.getTime() > pickEnd.getTime() && day != endDay) {
					return false
				}

				return true
			},
			timeConfirm(val) {
				if (this.legalTime(val)) {
					this.projectTime.startDate = val.startDate
					this.projectTime.endDate = val.endDate
				} else {
					this.$u.toast('开始或结束时间不能小于当前时间', 4000)
				}
				//console.log(val);
			},
			timeClose(val) {
				this.isTimePickerShow = val
			},
			upTimerPicker() {
				this.isTimePickerShow = true
			},
			PatientConfirm(list) {
				//console.log(111);
				//this.$store.commit('FilterTeamChoose',[])  //选标签，患者清空
				this.huanzheList = list
				//this.$store.commit('SUIFANGhuanzheSelected', list)
				this.showPatient = false
			},
			Userconfirm(list) {
				this.userList = list
				this.showUser = false
			},
			delUser(value, key) { //删除人员tags
				this.userList.forEach(v => {
					if (value == v) {
						v.check = false
					}
				})
			},
			addUser() {

			},
			upHuanzheFilter() {
				this.showPatient = true
				this.$nextTick(async () => {
					this.$refs.Patient.clearPageStatus()
					await this.$refs.Patient.getTeam()
					//console.log(this.$refs.Patient.list);
				})
				this.$store.commit('SUIFANGuserSelected', []) //选患者清标签  
			},
			async showinnerUser() {
				await register(['selectEnterpriseContact'])
				this.$ww.selectEnterpriseContact({
					fromDepartmentId: 0, //-1 表示从自己所在部门开始 0 表示从最上层开始
					mode: 'multi',
					type: ['department', 'user']
					// ,selectedDepartmentIds: ['2', '3'],
					// selectedUserIds: ['lisi', 'lisi2']
				})
			},
			upUserFilter() {
				this.showUser = true
				this.$nextTick(async () => {
					this.$refs.teamChild.clearPageStatus()
					await this.$refs.teamChild.getTeam()
					let teamList = this.$refs.teamChild.list
					if (teamList.length > 0) {
						teamList.forEach(v => {
							if (this.userList.length > 0) {
								this.userList.forEach(val => {
									if (val.userId == v.userId) {
										v.check = val.check
									}
								})
							}
						})
					}
				})
			},
			async postData() {
				const userId = uni.getStorageSync('userinfo').user.userId
				let params = {
					name: this.form.name, //计划名称
					planStartTime: this.projectTime.startDate, //计划周期开始
					planEndTime: this.projectTime.endDate, //计划周期结束时间
					//targetCustomerType:2                    //目标患者类型 2、患者标签 3、添加患者
					//teamOrUserId:80，

				}
				if (this.markSelected.length > 0) {
					params['targetCustomerType'] = 2
					params.customerTagIdList = this.markSelected
				}
				if (this.huanzheListSelected.length > 0) {
					params['targetCustomerType'] = 3
					params['externalUserIdList'] = this.huanzheListSelected.map(v => v.externalUserId)

				}
				if (uni.getStorageSync('myTeam')) { //有Team时，用teamId
					const teamId = uni.getStorageSync('myTeam').data.id
					params['teamOrUserId'] = teamId
				} else { //没团队用userid
					
					params['teamOrUserId'] = userId
				}
				if (this.userListSelected.length > 0) { //执行成员用户Id
					params.userIdList = this.userListSelected.map(v => v.userId)
				}
				if(!this.teamId){ //没有团队的清空下传自己的userId
					params.userIdList = [userId]
				}
				
				if (this.jobList.length > 0) {
					params.jobList = this.jobList
				}
				// console.log(params,456);
				// return
				if (this.planId) { //有计划id就是修改
					let res = await putPlan({
						...params,
						id: this.planId
					})
					if (res.code == 200) {
						uni.navigateTo({
							url: '/pages/follow/index'
						})
					}
				} else {
					// console.log(params);
					// return
					let res = await addPlan(params)
					if (res.code == 200) {
						uni.navigateTo({
							url: '/pages/follow/index'
						})
					}
				}
				//console.log(res, 123);
			},
			btConfirm(state) { //保存
				if (this.form.name.length > 15) {
					this.$u.toast('随访计划名称字数超出15个汉字', 3000)
					return
				}
				if (this.form.name.length < 3) {
					this.$u.toast('随访计划名称字数低于3个汉字', 3000)
					return
				}
				if (this.jobList.length == 0) {
					this.$u.toast('请填写任务规则', 3000)
					return
				}
				this.postData()

				// if (!state) {
				// 	console.log(state);
				// }
			},
			btFilterConfirm(val) {
				this.showPages = 1
			},
			toJobRule() {
				uni.navigateTo({
					url: '/pages/follow/rulejob'
				})
			},
			conditions(val) {
				this.showPages = 1
				this.currentCondition = val
				if (this.currentCondition == 'huanzhe') {
					this.upHuanzheFilter()
				}
				if (this.currentCondition == 'biaoqian') {
					this.showMark = true
					this.$nextTick(() => {
						this.$refs.markChild.getTeam() //只有在患者打标签时，拉起页面才去请求接口
					})
				}
			},
			closeMark(val) {
				this.MarkList = val //打标签选中标签  
				this.showMark = false
			},
			Markconfirm(list) {
				// if (list.markChoose.length == 0) {
				// 	this.$u.toast('至少应选择一个标签')
				// 	return
				// }
				this.editTagIdList = []
				this.MarkList = this.$u.deepClone(list.markChoose) //打标签选中标签

				this.MarkSelectLength = list.list.length //总长度
				this.MarkList.map(v => {
					this.editTagIdList.push(v.tagId)
				})
				//console.log(56756);
				this.$store.commit('SUIFANGuserSelected', this.editTagIdList)
				this.$store.commit('SUIFANGhuanzheSelected', []) //患者和标签二选一，这里选标签就把患者清了
				this.$store.commit('FilterTeamChoose', []) //双赋值，这个是别的地方用的，也要患者选中清了
				this.huanzheList = []
				this.showMark = false
				//this.postMark()
			},
		},
	}
</script>

<style lang="scss" scoped>
	.mains {
		background-color: #f8f8f8;
		// width: 100vw;
		// min-height: 80vh;
		// position: absolute;

		.card_box {
			margin-top: 20rpx;

			.top_card {
				background-color: #ffffff;
				padding-bottom: 40rpx;

				.card_title {
					padding-top: 24rpx;
					padding-left: 24rpx;
					padding-bottom: 12rpx;
					font-family: PingFang SC, PingFang SC;
					font-weight: bold;
					font-size: 32rpx;
					color: #212121;
					line-height: 38rpx;
				}

				.inputStyle {
					margin: 0 24rpx;
					background-color: #f8f8f8;
					padding: 10rpx 24rpx 10rpx 24rpx;
					border-radius: 20rpx;
					display: flex;
					justify-content: space-between;
					align-items: center;
					height: 76rpx;
					font-size: 32rpx;

					.line_title {
						font-family: PingFang SC, PingFang SC;
						// padding: 18rpx 24rpx;
						font-weight: 500;
						font-size: 32rpx;
						color: #333333;
						line-height: 38rpx;
					}

					.arrow_width {
						width: 60rpx;
						display: flex;
						justify-content: flex-end;
					}
				}

				.tips {
					padding: 18rpx 24rpx 24rpx 24rpx;
					font-family: PingFang SC, PingFang SC;
					font-size: 26rpx;
					color: #999999;
					line-height: 30rpx;
				}

				.tags_box {
					display: flex;
					//justify-content: space-between;
					font-weight: 500;
					font-size: 32rpx;
					color: #333333;
					line-height: 38rpx;

					//height: 60rpx;
					.tags {
						//background: #F2F2F2;
						background-color: #ffffff;
						border-radius: 12rpx;
						margin-right: 40rpx;
						position: relative;
						flex-shrink: 0;

						.tags_title {
							padding: 8rpx 36rpx;
						}

						.x_img {
							position: absolute;
							top: 0;
							right: -20rpx;
						}
					}
				}
			}

			.job_rule {
				display: flex;
				justify-content: space-between;
				font-family: PingFang SC, PingFang SC;
				// padding: 18rpx 24rpx;
				background-color: white;
				margin-top: 20rpx;
				font-weight: bold;
				font-size: 32rpx;
				color: #212121;
				line-height: 38rpx;
				padding: 24rpx;
				border-bottom: 1px solid #f7f7f7;

				.job_add {
					font-family: PingFang SC, PingFang SC;
					font-weight: 500;
					font-size: 30rpx;
					color: #4DC0D9;
					line-height: 35rpx;
				}
			}

			.rule_box {
				background-color: #ffffff;
				padding-bottom: 1000rpx;

				.rule_card {
					padding-top: 24rpx;
					padding-left: 24rpx;
					height: 304rpx;
					display: flex;
					flex-direction: column;
					//align-items: center;
					justify-content: center;

					.rule_step {
						.dot {
							display: flex;
							align-items: center;

							.time_title {
								margin-left: 8rpx;
								font-weight: 500;
								font-size: 32rpx;
								color: #999999;
								//line-height: 1.5;
							}
						}
					}

					.rule_content {
						//padding-left: 40rpx;
						padding-left: 24rpx;
						margin-left: 5px;
						height: 266rpx;
						border-left: 1px dashed #ccc;
						font-weight: bold;
						font-size: 34rpx;
						color: #212121;
						line-height: 42rpx;

						.rule_content_title {
							margin-top: 6rpx;
							display: flex;

							.base_icon {
								padding: 4rpx 6rpx 6rpx 6rpx;
								width: 70rpx;
								height: 40rpx;
								background: #FF8D07;
								font-weight: 500;
								font-size: 24rpx;
								color: #FFFFFF;
								text-align: center;
								line-height: 28rpx;
								border-radius: 8rpx;
								display: flex;
								align-items: center;
								justify-content: center;
							}

							.zhouqi {
								background: #FF8D07;
							}

							.dingshi {
								background-color: #4DC0D9;
							}
						}

						.rule_content_details {
							margin-top: 12rpx;
							padding-right: 24rpx;
							font-size: 30rpx;
							color: #666666;
							line-height: 1.5;
						}

						.rule_content_action {
							margin: 20rpx 24rpx 60rpx 0;
							display: flex;
							justify-content: flex-end;
							font-weight: 500;
							font-size: 30rpx;
							color: #4DC0D9;
							line-height: 1.5;

							.edit {
								margin-right: 48rpx;
							}

							.del {}
						}
					}
				}
			}
		}

	}

	::v-deep .u-input__input {
		font-size: 32rpx;
	}
</style>